<template>
  <div>
    <a-page-header title="权限分配" :ghost="false" sub-title="基础组件" />
    <a-card class="mt-1" :bordered="false">
      <a-list :grid="{ gutter: 16, column: 1 }" :data-source="data">
        <template #renderItem="{ item }">
          <a-list-item>
            <a-card size="small" :bordered="false">
              <template #title>
                {{ item.name }}
              </template>
              <a-checkbox-group
                v-model:value="permissions[`${item.name}`]"
                :options="
                  item.children.map((v) => ({ label: v.name, value: v.code }))
                "
              />
            </a-card>
          </a-list-item>
        </template>
      </a-list>
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </a-card>
  </div>
</template>


<script lang="ts">
import {
  defineComponent,
  onBeforeUpdate,
  onMounted,
  reactive,
  Ref,
  ref,
} from "vue";
import {
  Card,
  PageHeader,
  Tabs,
  List,
  Checkbox,
  Button,
  message,
} from "ant-design-vue";
import { useRoute } from "vue-router";
import { getPermissions } from "@/api/permission";
import { Permission } from "@/types";
import { assgin } from "@/api/role";

interface Permissions {
  [key: string]: any;
}

export default defineComponent({
  components: {
    ACheckbox: Checkbox,
    ACheckboxGroup: Checkbox.Group,
    AList: List,
    AListItem: List.Item,
    ATabs: Tabs,
    ATabPane: Tabs.TabPane,
    ACard: Card,
    APageHeader: PageHeader,
    AButton: Button,
  },
  setup() {
    const route = useRoute();
    console.log("Role ID:", route.params.code);
    const data: Ref<Permission[]> = ref([]);
    const permissions: Permissions = ref({});

    onMounted(() => {
      console.log("onMounted");
      Promise.all([
        getPermissions(),
        getPermissions(<string>route.params.code),
      ]).then((res: any) => {
        data.value = res[0].data;
        permissions.value = res[1].data;
      });
    });

    onBeforeUpdate(() => {
      console.log("onBeforeUpdate");
      getPermissions(<string>route.params.code).then((res: any) => {
        permissions.value = res.data;
      });
    });

    const handleSubmit = async () => {
      let res = [];
      console.log(permissions.value);
      for (const key of Object.keys(permissions.value)) {
        const value = permissions.value[key];
        res.push(...value);
      }

      const response = await assgin(<string>route.params.code, res);
      if (response != undefined && response.status == 200) {
        message.success(response.message);
      }
    };

    return { data, permissions, handleSubmit };
  },
});
</script>

<style lang="less" scoped>
</style>
